package com.wudl.wudllogger.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wudl.common.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName : LoggerController
 * @Description : 日志收集
 * @Author :wudl
 * @Date: 2020-09-21 22:57
 */

@RestController
public class LoggerController {

    private Logger logger = LoggerFactory.getLogger(LoggerController.class);

    @Autowired
    KafkaTemplate template;

    @PostMapping(value = "/log")
    public String sendData(@RequestParam("log") String log) {
        log = addTs(log);
        System.out.println(log);
        saveLog(log);
        //写到kafka  先创建kafak生产者 再调生产者send方法
        sendToKafka(log);
        return "ok";
    }


    private String addTs(String log) {
        JSONObject obj = JSON.parseObject(log);
        obj.put("ts", System.currentTimeMillis());
        return obj.toJSONString();
    }

    private void saveLog(String log) {
        logger.info(log);
    }


    private void sendToKafka(String log) {
        String topic = Constant.TOPIC_STARTUP;
        if (log.contains("event")) {
            topic = Constant.TOPIC_EVENT;
        }
        template.send(topic, log);
    }

}
